<template>
  <div class="Login">
    <nav-bar :title="title" :left-arrow="true"></nav-bar>
    <div class="img">
      <img src="//es-static.xiaojukeji.com/static/web/home/index202006/home/images/page22-a54b581bb0.png" alt="">
    </div>
    <div class="formBox">
      <van-form @submit="onSubmit">
        <van-field
          v-model="username"
          name="用户名"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="password"
          type="password"
          name="密码"
          label="密码"
          placeholder="密码"
          :rules="loginRules.password"
        />
        <div style="margin: 16px;">
          <van-button round block type="info" native-type="submit">提交</van-button>
        </div>
      </van-form>
    </div>
    <div class="message">
      <router-link to='/register'>
        <p>去注册</p>
      </router-link>
    </div>
  </div>
</template>

<script>
import NavBar from '@/components/NavBar/index'
import { login } from '@/api/user'
import { mapMutations } from 'vuex'
export default {
  name: 'Tabs',
  components: {
    NavBar
  },
  data () {
    return {
      title: '登录',
      username: '',
      password: '',
      params: {},
      loginRules: {
        password: [
          { required: true, message: '', trigger: 'onBlur' },
          { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/, message: '密码至少8个字符，至少1个大写字母，1个小写字母和1个数字' }
        ]
      }
    }
  },
  methods: {
    ...mapMutations([
      'setLogin',
      'setUser'
    ]),
    async onSubmit (values) {
      const params = {}
      for (var key of Object.keys(values)) {
        if (key === '密码') {
          params.password = values[key]
        } else {
          params.username = values[key]
        }
      }
      // 发送登录请求
      const { data: res } = await login(params)
      if (res.meta.status === 200) {
        console.log(res)
        this.$notify({ type: 'success', message: '登陆成功，页面即将跳转' })
        params.isDetail = false
        params.userId = res.data
        this.params = params
        // 是否填写详情
        this.setLogin(true)
        this.setUser(this.params)
        setTimeout(() => {
          this.$router.push('/home')
        }, 1000)
      } else {
        const msg = res.meta.msg
        this.$notify({ type: 'danger', message: msg })
      }
    }
  }
}
</script>

<style scoped lang="scss">
.img{
  margin-top: 20px;
  height: 200px;
  width: 100%;
  img{
    width: 100%;
    height: 100%;
  }
}
.formBox{
  margin-top: 20%;
}
.message{
  p{
    margin-left: 80%;
    color: rgba(0,0,0,.4);
  }
}
</style>
